//
//  CYTime.m
//  CaiYun
//
//  Created by 今日信息科技 on 2017/8/14.
//  Copyright © 2017年 今日信息科技. All rights reserved.
//

#import "YJDTime.h"
@interface YJDTime(){
    dispatch_source_t _timer;
}
@end
@implementation YJDTime
- (instancetype)init{
    self = [super init];
    if (self) {
        
    }
    return self;
}

- (void)yjd_countDown:(int)number time:(void(^)(NSString *time))time complete:(void(^)(void))complete{
    __block int new_number = number;
    dispatch_queue_t global = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);//获取全局队列
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, global);//创建定时器，并将定时器的任务交给全局队列
    dispatch_source_set_timer(_timer, DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC, 0.01 * NSEC_PER_SEC);//设置出发的间隔时间，第三个参数，代表设置定时器触发的时间间隔 1.0s  第四个参数  代表时间允许的误差是 0s
    dispatch_source_set_event_handler(_timer, ^{ //定时器的触发事件
        if (new_number <= 0){
            [self yjd_cancel];//关闭定时器
            if (complete)
                dispatch_async(dispatch_get_main_queue(), ^{
                    complete();//完成回调
                });
        }
        else
            dispatch_async(dispatch_get_main_queue(), ^{
                time([NSString stringWithFormat:@"%d",new_number]); //将number，转换成时间格式，并且通过主队列，传递出去
            });
        new_number --;//递减
    });
    dispatch_resume(_timer);
    
}

- (void)yjd_cancel{
    if (_timer)//如果定时器存在
        dispatch_source_cancel(_timer);//释放定时器
}

+ (NSArray *)timeArray{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"MM,dd,HH,mm"];//此处不需要用到年，所以去掉yyy
    NSDate *date = [NSDate date];
    NSString *time = [formatter stringFromDate:date];
    return [time componentsSeparatedByString:@","];
}
@end
